import json
from models.dao import role_dao, role_permission_dao, user_role_dao
from models.database import SessionLocal

def getRoles(skip: int = 0, limit: int = 100):
    """
    获取角色列表，返回符合前端SystemRoleApi.SystemRole接口格式的数据
    """
    with SessionLocal() as db:
        roles = role_dao.getRoles(db, skip=skip, limit=limit)
        # 使用角色的to_dict方法，确保返回前端需要的格式
        return [r.to_dict() for r in roles]

def get_roles_count():
    """
    获取角色总数
    """
    with SessionLocal() as db:
        return role_dao.get_roles_count(db)

def getRole(role_id: str):
    """
    根据ID获取单个角色，返回符合前端SystemRoleApi.SystemRole接口格式的数据
    """
    with SessionLocal() as db:
        roleModel = role_dao.getRole(db, role_id=role_id)
        if roleModel is None:
            return None
        return roleModel.to_dict()

def createRole(role_data: dict):
    """
    创建新角色，并处理其权限
    """
    with SessionLocal() as db:
        # 分离权限和其他角色数据
        permission_ids = role_data.pop('permissions', [])
        
        # 如果 permission_ids 是字符串格式的 JSON 数组，则解析它
        if isinstance(permission_ids, str):
            try:
                permission_ids = json.loads(permission_ids)
            except json.JSONDecodeError:
                permission_ids = []
        
        # 创建角色
        new_role = role_dao.createRole(db, role_data)
        if not new_role:
            return None
        
        # 为新角色添加权限
        if permission_ids:
            for perm_id in permission_ids:
                role_permission_dao.createRolePermission(db, {'role_id': new_role.id, 'permission_id': perm_id})
        
        db.refresh(new_role)
        return new_role.to_dict()

def updateRole(role_id: str, role_data: dict):
    """
    更新角色，并处理其权限
    """
    try:
        with SessionLocal() as db:
            # 分离权限和其他角色数据
            permission_ids = role_data.pop('permissions', [])

            # 如果 permission_ids 是字符串格式的 JSON 数组，则解析它
            if isinstance(permission_ids, str):
                try:
                    permission_ids = json.loads(permission_ids)
                except json.JSONDecodeError:
                    permission_ids = []

            # 更新角色基本信息
            updated_role = role_dao.updateRole(db, role_id, role_data)
            if not updated_role:
                return None

            # 更新角色权限
            if permission_ids:
                # 删除旧权限
                role_permission_dao.delete_role_permissions_by_role_id(db, role_id)

                # 添加新权限
                for perm_id in permission_ids:
                    role_permission_dao.createRolePermission(db, {'role_id': role_id, 'permission_id': perm_id})

            db.refresh(updated_role)
            return updated_role.to_dict()
    except Exception as e:
        return None

def deleteRole(role_id: str):
    """
    删除角色及其关联数据
    """
    with SessionLocal() as db:
        # Check if role exists
        role_to_delete = role_dao.getRole(db, role_id)
        if role_to_delete is None:
            return False

        # Delete associated role permissions
        role_permission_dao.delete_role_permissions_by_role_id(db, role_id)

        # Delete associated user roles
        user_role_dao.delete_user_roles_by_role_id(db, role_id)

        # Delete the role itself
        return role_dao.deleteRole(db, role_id=role_id)

def get_all_role_names():
    """
    获取所有角色名称
    """
    with SessionLocal() as db:
        roles = role_dao.get_all_roles(db)
        return {role.name for role in roles}

def get_all_roles():
    """
    获取所有角色
    """
    with SessionLocal() as db:
        roles = role_dao.get_all_roles(db)
        return [r.to_dict() for r in roles]

def get_system_roles(page: int = 1, page_size: int = 20, role_name: str = None, status: str = None, 
                    role_id: str = None, remark: str = None, create_time_start: str = None, create_time_end: str = None):
    """
    获取系统角色列表（支持分页和过滤），并附带权限ID
    """
    with SessionLocal() as db:
        # 计算skip
        skip = (page - 1) * page_size
        
        # 获取分页和过滤后的角色
        roles = role_dao.getRoles(db, skip=skip, limit=page_size, role_name=role_name, status=status, 
                                role_id=role_id, remark=remark, create_time_start=create_time_start, 
                                create_time_end=create_time_end)
        total_count = role_dao.get_roles_count(db, role_name=role_name, status=status, role_id=role_id, 
                                             remark=remark, create_time_start=create_time_start, 
                                             create_time_end=create_time_end)
        
        # 构建返回数据
        role_list = []
        for role in roles:
            # 获取角色的权限ID列表
            permissions = role_permission_dao.get_permissions_by_role_id(db, role.id)
            permission_ids = [p.permission_id for p in permissions]
            
            # 格式化角色数据
            role_data = role.to_dict()
            role_data['roleCode'] = permission_ids # 将权限ID列表赋值给roleCode
            role_list.append(role_data)
            
        return {
            "items": role_list,
            "total": total_count
        }